-- 创建聊天框状态检测框架
local ChatDetector = CreateFrame("Frame")
ChatDetector:RegisterEvent("PLAYER_ENTERING_WORLD")
ChatDetector:RegisterEvent("UPDATE_CHAT_WINDOWS")
ChatDetector:RegisterEvent("CHAT_MSG_SAY")
ChatDetector:RegisterEvent("CHAT_MSG_WHISPER")
ChatDetector:RegisterEvent("CHAT_MSG_CHANNEL")
ChatDetector:RegisterEvent("CHAT_MSG_YELL")
ChatDetector:RegisterEvent("CHAT_MSG_EMOTE")
ChatDetector:RegisterEvent("CHAT_MSG_GUILD")
ChatDetector:RegisterEvent("CHAT_MSG_PARTY")
ChatDetector:RegisterEvent("CHAT_MSG_RAID")
ChatDetector:RegisterEvent("CHAT_MSG_RAID_WARNING")
ChatDetector:RegisterEvent("CHAT_MSG_INSTANCE_CHAT")

-- 状态变量
local isChatting = false
local lastChatType = nil

-- 事件处理
ChatDetector:SetScript("OnEvent", function(self, event, ...)
    if event == "PLAYER_ENTERING_WORLD" then
        -- 初始化
        self:InitializeChatDetection()
    elseif event == "UPDATE_CHAT_WINDOWS" then
        -- 聊天窗口更新时检测
        self:CheckChatStatus()
    elseif event:sub(1, 8) == "CHAT_MSG" then
        -- 聊天消息事件
        local messageType = event:sub(10)
        if messageType == "SAY" or messageType == "WHISPER" or
                messageType == "CHANNEL" or messageType == "YELL" or
                messageType == "EMOTE" or messageType == "GUILD" or
                messageType == "PARTY" or messageType == "RAID" or
                messageType == "RAID_WARNING" or messageType == "INSTANCE_CHAT" then
            -- 记录最后使用的聊天类型
            lastChatType = messageType
        end
    end
end)

-- 初始化聊天检测
function ChatDetector:InitializeChatDetection()
    -- 设置初始状态
    isChatting = false

    -- 添加状态检测脚本
    self:SetScript("OnUpdate", function(self, elapsed)
        self:CheckChatStatus()
    end)

    print("聊天框状态检测已启用")
end

-- 检测聊天框状态
function ChatDetector:CheckChatStatus()
    -- 获取当前激活的聊天框
    local editBox = ChatEdit_GetActiveWindow()

    if editBox then
        -- 聊天框激活状态
        if not isChatting then
            isChatting = true
            self:OnChatStart(editBox)
        end
    else
        -- 聊天框非激活状态
        if isChatting then
            isChatting = false
            self:OnChatEnd()
        end
    end
end

-- 聊天开始回调
function ChatDetector:OnChatStart(editBox)
    -- 获取当前聊天类型
    local chatType = editBox:GetAttribute("chatType") or lastChatType or "SAY"

    -- 打印状态信息
    print(format("聊天框激活 | 类型: %s", chatType))

    -- 可以在这里添加自定义逻辑
    -- 例如：隐藏某些UI元素
end

-- 聊天结束回调
function ChatDetector:OnChatEnd()
    print("聊天结束")

    -- 可以在这里添加自定义逻辑
    -- 例如：恢复UI元素显示
end

-- 添加斜杠命令测试
SLASH_CHATSTATUS1 = "/chatstatus"
SlashCmdList["CHATSTATUS"] = function()
    local editBox = ChatEdit_GetActiveWindow()
    if editBox then
        print("当前正在聊天框中输入")
        print(format("聊天类型: %s", editBox:GetAttribute("chatType") or "未知"))
    else
        print("当前没有在聊天框中输入")
    end
end

-- 初始打印
print("聊天框状态检测插件已加载")
print("输入 /chatstatus 查看当前状态")